package io.sage.modules.rxtx.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import io.sage.modules.rxtx.service.RxtxService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import io.sage.common.config.WebSocketServer;
import io.sage.common.rxtx.PrivateStringFormat;
import io.sage.common.rxtx.RxtxConfig;
import io.sage.common.utils.CheckNullUtils;
import io.sage.common.utils.R;
import io.sage.common.utils.StringUtils;
import uhf.AsyncSocketState;

/**
 * Created by Mafy on 2019/6/5.
 *  读写器基本操作，获取com口，serverip，客户端对象、读取无源标签、停止读取标签等操作
 */
@RestController
@RequestMapping("/rxtx")
public class SrController {

    @Resource
    private RxtxConfig rxtxConfig;

//    @Autowired
//    private SysConfigRedis sysConfigRedis;


    //获取端口是否开启
    @RequestMapping("/getComIpUsing")
    public R getComIpUsing(){
        return R.ok().put("comList",null);
    }

    //获取本机com口
    @RequestMapping("/getCom")
    public R getCom(){
        rxtxConfig.GetCom();
        List<String> rxtxComList =  rxtxConfig.GetCom();
        return R.ok().put("comList",rxtxComList);
    }
    //获取本机ip
    @RequestMapping("/getServerIp")
    public R getServerIp(){
        List<String> localIPList = rxtxConfig.getLocalIPList();
        return R.ok().put("localIPList",localIPList);
    }



    //打开或关闭com服务
    @RequestMapping("/comServerAction")
    public R comServerAction(boolean isOpen,String comName){

        int index = CheckNullUtils.checkNotNullParam(isOpen,comName);
        String result = CheckNullUtils.getNullParamName(index,"isOpen","comName");
        if (!StringUtils.equals(result,"0")){
            return R.error(result);
        }
        boolean isAction = rxtxConfig.comServerAction(isOpen,comName,-1);
        return R.ok().put("isAction",isAction);
    }

    //打开或关闭ip服务
    @RequestMapping("/ipServerAction")
    public R ipServerAction(boolean isOpen,String serverIp,int serverPort){
        //serverIp="192.168.1.80";
        int index = CheckNullUtils.checkNotNullParam(isOpen,serverIp,serverPort);
        String result = CheckNullUtils.getNullParamName(index,"isOpen","serverIp","serverPort");
        if (!StringUtils.equals(result,"0")){
            return R.error(result);
        }
        boolean isAction = false;
        try {
            isAction = rxtxConfig.ipServerAction(isOpen,serverIp,serverPort);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok().put("isAction",isAction);
    }

    //获取客户端对象--这里不区分是1个还是多个，都需要在页面选择一下
    @RequestMapping("/getClientInfo")
    public R getClientInfo(){
        List<AsyncSocketState> clientInfo = rxtxConfig.getClientInfo();
        List<Map<String,Object>> clientList = new ArrayList<>();

        if(!ObjectUtils.isEmpty(clientInfo)){
            for (int i = 0; i < clientInfo.size(); i++) {
                Map<String,Object> evClient = new HashMap<>();
                evClient.put("index",i);
                evClient.put("port",clientInfo.get(i).port);
                evClient.put("dev", PrivateStringFormat.GetDevice(clientInfo.get(i).dev));
                if (clientInfo.get(i).types.equals("NET")) // 网口
                {
                    evClient.put("ip",clientInfo.get(i).ip_addr);
                    evClient.put("state",clientInfo.get(i).state);
                } else if (clientInfo.get(i).types.equals("COM")) // 串口
                {
                    evClient.put("ip",clientInfo.get(i).com);
                    evClient.put("state","");
                }
                clientList.add(evClient);
            }
        }
//        for (int i = 0; i < 15; i++) {
//                Map<String,Object> evClient = new HashMap<>();
//                evClient.put("index",i);
//                evClient.put("port","6000");
//                evClient.put("dev", "ss");
//                evClient.put("ip","192.168.4.168");
//                evClient.put("state","1");
//                clientList.add(evClient);
//        }
        return R.ok().put("clientList",clientList);
    }

    //确定客户端对象
    @RequestMapping("/checkClient")
    public R checkClient(@RequestBody JSONObject jsonObject){
        int index = jsonObject.getInteger("index");
        if(ObjectUtils.isEmpty(index)){
            return R.error("index 不可为空");
        }
        try {
            rxtxConfig.setCurrentclient(rxtxConfig.getAsyncSocketStates().get(index));
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }

    //读取无源标签
    @RequestMapping("/readEPC")
    public R readEPC(){
        try {
            boolean b = rxtxConfig.StartMultiEPC();
//            String[] result = rxtxConfig.getResultData();
//            if(b && !ObjectUtils.isEmpty(result)){
//                String Device = PrivateStringFormat.GetDevice(result[0]);
//                System.err.println("Ant:"+result[4]+"\r\n"+"EPC:"+result[5]+"\r\n"
//                        +"PC:"+result[6]+"\r\n"+"RSSI:"+result[7]+"\r\n"+"DevID:"+Device+"\r\n"
//                        +"ReadTime:"+result[12]+"\r\n"+"Dir:"+result[9]+"\r\n"+"TID:"+result[13]);
//                return R.ok().put("result",result);
//            }
            return R.ok().put("isStart",b);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器异常");
        }
    }

    //停止无源标签
    @RequestMapping("/stopEPC")
    public R stopEPC(){
        boolean b = false;
        try {
            b = rxtxConfig.StopMultiEPC();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器异常");
        }
        return R.ok().put("isStop",b);
    }

    //socket测试
    @RequestMapping("/socket/push/{cid}")
    public R testWebsocket(@PathVariable String cid, String message){
        try {
            WebSocketServer.sendInfo(message,cid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @Resource
    private RxtxService rxtxService;

    @RequestMapping("/rfid")
    public R testRfid(@RequestBody JSONObject jsonObject){
        String lableid = jsonObject.getString("id");
        rxtxService.lableDataHandle(lableid);
        return R.ok();
    }
}
